package com.ag.zhh.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.ag.bean.TbDeptType;
import com.ag.common.BaseAction;
import com.ag.contactTree.TreeNode;
import com.ag.contactTree.service.LocalTreeService;
import com.ag.contactTree.service.TreeService;
import com.ag.zhh.service.ContactService;
import com.ag.zhh.service.LocalDeptService;
import com.ag.zhh.service.OADeptService;
import com.ag.zhh.utils.DeptIDUtil;
import com.ag.zhh.utils.JsonUtil;
import com.ag.zhh.vo.Contact;
import com.ag.zhh.vo.UserDept;
import com.ag.zhh.vo.UserDeptContact;

//本地部门的维护
public class DeptAction extends BaseAction {

	private String udId; // 部门id
	private String udName; // 部门名
	private String udTel; // 电话
	private String udPhone; // 手机
	private String udIf; // 是否通知部门
	private String fDId; // 父部门id
	private String dtypeId; // 部门类型id
	private String leader;		//负责人id
	private String leaderName; 	//	负责人名
	private String udFax; // 传真
	private List<UserDept> depts; // 部门列表,事件通知时用到
	private List<UserDeptContact> users; // 部门的联系人
	private UserDept userDept; // 上级部门
	// 更新和增加dept需要的参数ends
	private ContactService contactService;
	private Map<String, String> difs;
	private String result;
	private String nodeId; // 获取节点请求参数
	private String deptString;// dept节点响应JSON字符串
	private String fdeptName; // 父部门id
	private LocalDeptService deptService;
	private LocalTreeService treeService;
	
	public String setDeptDIfs() throws Exception {
		
		List<String> setList = new ArrayList<String>();
		List<String> resetList = new ArrayList<String>();
		for (String str : difs.keySet()) {
			System.out.println(difs.get(str));

			// 更新树
			TreeNode node = treeService.getTreeNodeById(str);
			if (difs.get(str).equals("true")) {
				((UserDept) node.getBindData()).setUdIf(new Long(1));
				setList.add(str);
			} else {
				((UserDept) node.getBindData()).setUdIf(new Long(0));
				resetList.add(str);
			}
		}

		try {
			deptService.setDeptDIfOnly(setList);
			deptService.resetDeptDIfOnly(resetList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		this.setResult("success!");
		return "setDeptDIfs";
	}

	/**
	 * 完成
	 * 
	 * @return
	 */
	public String saveOrUpdateDept() {

		UserDept dept = null;
		TreeNode fnode;
		try {

			System.out.println("deptAction: udId=" + udId + " udName:" + udName
					+ " udTel:" + udTel + " udPhone:" + udPhone + " udIf:"
					+ udIf + " fDId:" + fDId + " dtypeId:" + dtypeId);

		} catch (Exception e) {
			e.printStackTrace();
		}
		if (udId == null || udId.isEmpty()) // 增加
		{
			String newId = null;
			try {
				System.out.println("**************" + "增加");
				dept = new UserDept();
				// 分配新的部门ID
				fnode = treeService.getTreeNodeById(fDId);
				// 测试：TreeNode fnode = new TreeNode();
				newId = fDId.substring(0, 2)
						+ DeptIDUtil.getNewDeptIDByFDId(fDId.substring(2),
								fnode.getChildren());
				System.out.println("newId:\t" + newId);
				TbDeptType deptType = new TbDeptType();
				System.out.println("dTypeId :" + dtypeId);
					deptType.setDtId(((UserDept)fnode.getBindData()).getTbDeptType().getDtId());
				System.out.println("deptTypeId:\t" + deptType.getDtId());
				dept.setUdId(newId); // 部门id
				if (udIf!=null && udIf.equals("true"))
					dept.setUdIf(new Long(1));
				else
					dept.setUdIf(new Long(0));
				dept.setUdName(udName);
				dept.setTbDeptType(deptType); // 部门类型
				dept.setTbUserDept((UserDept) fnode.getBindData()); // 父部门
				dept.setUdFax(udFax); // 部门联系方式
				dept.setUdPhone(udPhone);
				dept.setUdTel(udTel);
				treeService.addTreeNodeByUserDept(dept, deptType.getDtId());
				// treeService.addTreeNodeByDept(dept, deptType);
			} catch (Exception e) {

//				if (e.getMessage().equals("DeptIDUtil：超出层数限制，不能增加子部门")) {
//					this.setResult("增加部门失败！超出部门树层数限制！");
//					System.out.println("增加部门失败！超出部门树层数限制！");
//				}
				e.printStackTrace();

			}

		} else { // 更新
			// 从树服务对象查找dept树节点

			try {
				TreeNode node = treeService.getTreeNodeById(udId);
			
					System.out.println("**************** deptAction: dId="
							+ udId);
		
				System.out.println("**************" + "更新");

				dept = (UserDept) node.getBindData();
				System.out.println("更新过程的部门的id可以拿到吗？ deptId: "+dept.getUdId());
				System.out.println("更新过程的部门的类型可以拿到吗？ deptTypeId: "+dept.getTbDeptType().getDtId());
				if (udIf != null) {
					if (udIf.equals("true"))
						dept.setUdIf(new Long(1));
					else
						dept.setUdIf(new Long(0));
				}

				dept.setUdName(udName);
				dept.setUdPhone(udPhone);
				dept.setUdFax(udFax);
				dept.setUdTel(udTel);

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		try {
			
			UserDeptContact user=null;
			System.out.println("------------" + dept.getUdIf());
			if(leader!=null&&!leader.equals("noneUser"))
			{
				user = contactService.findCotnactByCId(leader);
				user.setUId(leader);
				dept.setTbUser(user);
			}
			else dept.setTbUser(null);
			
			System.out.println("更新部门之前：部门id：" + dept.getUdId() + " 部门名："
					+ dept.getUdName() + "  手机：" + dept.getUdPhone() + "  电话："
					+ dept.getUdTel() + " 父部门id："+udIf
					+"部门类型："+dept.getTbDeptType().getDtId());
			if(user!=null){
				System.out.println(" 负责人id："+user.getUId()+"  负责人名："+user.getUName());
			}
					
			deptService.saveOrUpdateDept(dept);

			this.setResult("success!");

			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "saveOrUpdateDept";
	}
	/**
	 * 查找负责人
	 * @return
	 */
	public String findLeader()
	{
	
		try {
			users = contactService.findContactByName(leaderName);
			if(users==null||users.size()==0) result="1000";			//匹配不成功
			else if(users.size()==1) result="1001";	//刚好找到一个
			else result="1002";
			System.out.println("用户名："+leaderName+"查出来的用户数目："+users.size());
		} catch (Exception e) {
			
			// TODO Auto-generated catch block
			e.printStackTrace();
		}						//匹配多个
		return "findusers";
	}
	/**
	 * 问题：上传的dept是同一个对象，所以要复制一个新的对象
	 * 
	 * @return
	 */
	public String deleteDept()// 删除部门
	{
		deptService.deleteDept(udId);
		try {
			System.out.println("被删除的部门: " + udId);
			System.out.println("被删除部门的父部门: fDId: " + fDId);
			TreeNode pnode = treeService.getTreeNodeById(fDId); // 获取父节点
			if (udId.equals(fDId)) // 若被删结点是当前结点
			{
				pnode = treeService.getTreeNodeById(udId).getParent();
			}
			if (pnode != null) {
				List<TreeNode> childrens = pnode.getChildren();
				if (childrens != null)
					for (TreeNode cnode : childrens) {
						System.out.println("\t\t树的id： " + cnode.getNodeId());
						if (cnode.getNodeId().equals(udId)) {
							childrens.remove(cnode);
							break;
						}
					}
			}

			result = "deleteSuccess";
			System.out.println("删除部门的action：result" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "deleteDept";
	}

	public String getDeptByNodeId() throws Exception {
		TreeNode node = treeService.getTreeNodeById(nodeId);
		// 获取要通过Json传输的对象
		UserDept bindingDept = (UserDept) node.getBindData();
		// 复制Dept对象
		UserDept dept = cloneDept(bindingDept);

		Set<UserDeptContact> contacts = dept.getTbUsers();
		UserDept FDept = dept.getTbUserDept();

		// 不指向的dept属性
		dept.setTbUsers(null);
		dept.setTbUserDept(null);
		// dept.setDLogoUrl(null);
		// dept.setTbDeptType(null);

		this.setDeptString(JsonUtil.beanToJson(dept));
		if (FDept != null)
			this.setFdeptName(FDept.getUdName());

		// 不指向所属部门
		// for (Contact c : contacts) {
		// c.setDept(null);
		// }
		return "getDeptByNodeId";
	}

	private UserDept cloneDept(UserDept dept) {
		UserDept newDept = new UserDept();

		newDept.setTbUsers(dept.getTbUsers());
		newDept.setTbUserDept(dept.getTbUserDept());
		// newDept.setDAddress(dept.getDAddress());
		newDept.setUdId(dept.getUdId());
		newDept.setUdIf(dept.getUdIf());
		newDept.setUdName(dept.getUdName());

		// newDept.setTbDeptType(dept.getTbDeptType());

		return newDept;
	}

	// 更新和增加dept需要的参数 starts

	// 查询部门列表,访问路径 /ag/do/dept_findDept.action
	public String findDept() throws Exception {
		depts = deptService.findDept();
		for (UserDept dept : depts) {
			System.out.println(dept.getUdName());
		}
		result = "find_Dept";
		return "find_Dept";
	}

	public String getUdId() {
		return udId;
	}

	public void setUdId(String udId) {
		this.udId = udId;
	}

	public String getUdName() {
		return udName;
	}

	public void setUdName(String udName) {
		this.udName = udName;
	}

	public String getUdTel() {
		return udTel;
	}

	public void setUdTel(String udTel) {
		this.udTel = udTel;
	}

	public String getUdPhone() {
		return udPhone;
	}

	public void setUdPhone(String udPhone) {
		this.udPhone = udPhone;
	}

	public String getUdIf() {
		return udIf;
	}

	public void setUdIf(String udIf) {
		this.udIf = udIf;
	}

	public String getFDId() {
		return fDId;
	}

	public void setFDId(String fDId) {
		this.fDId = fDId;
		System.out.println("父部门：fDId: " + this.fDId);
	}

	public String getfDId() {
		return fDId;
	}

	public void setfDId(String fDId) {
		this.fDId = fDId;
	}

	public String getDtypeId() {
		return dtypeId;
	}

	public void setDtypeId(String dtypeId) {

		this.dtypeId = dtypeId;
	}

	public String getUdFax() {
		return udFax;
	}

	public void setUdFax(String udFax) {
		this.udFax = udFax;
	}

	public List<UserDept> getDepts() {
		return depts;
	}

	public void setDepts(List<UserDept> depts) {
		this.depts = depts;
	}

	public List<UserDeptContact> getUsers() {
		return users;
	}

	public void setUsers(List<UserDeptContact> users) {
		this.users = users;
	}

	public UserDept getUserDept() {
		return userDept;
	}

	public void setUserDept(UserDept userDept) {
		this.userDept = userDept;
	}

	public Map<String, String> getDifs() {
		return difs;
	}

	public void setDifs(Map<String, String> difs) {
		this.difs = difs;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getNodeId() {
		return nodeId;
	}

	public void setNodeId(String nodeId) {
		this.nodeId = nodeId;
	}

	public String getDeptString() {
		return deptString;
	}

	public void setDeptString(String deptString) {
		this.deptString = deptString;
	}

	public String getFdeptName() {
		return fdeptName;
	}

	public void setFdeptName(String fdeptName) {
		this.fdeptName = fdeptName;
	}

	public LocalDeptService getDeptService() {
		return deptService;
	}

	public void setDeptService(LocalDeptService deptService) {
		this.deptService = deptService;
	}

	public LocalTreeService getTreeService() {
		return treeService;
	}

	public void setTreeService(LocalTreeService treeService) {
		this.treeService = treeService;
	}

	public String getLeader() {
		return leader;
	}

	public void setLeader(String leader) {
		this.leader = leader;
	}

	public String getLeaderName() {
		return leaderName;
	}

	public void setLeaderName(String leaderName) {
		this.leaderName = leaderName;
	}

	public ContactService getContactService() {
		return contactService;
	}

	public void setContactService(ContactService contactService) {
		this.contactService = contactService;
	}

}
